#include <filetransfferstruct.h>

void FileTransfferStruct::close()
{
	if (file_.is_open()) {
		file_.close();
	}
}

bool FileReadStruct::openFile(const std::string& fileName)
{
	fileName_ = fileName;
	if (!std::filesystem::exists(fileName)) {
		return false;	
	}
	file_.open(fileName, std::ios::in | std::ios::binary);
	fileSize_ = getFileSize(); // 获取文件大小
	return file_.is_open();
}

std::size_t FileReadStruct::processBytes(char* buffer, size_t size)
{
	memset(buffer, 0, size);
	size_t byteRead = readBytes(buffer, size);
	bytesHasRead_ += byteRead; // 更新文件被读的字节数
	++seq_;
	return byteRead;
}

std::size_t FileReadStruct::readBytes(char* buffer, size_t size)
{
	std::size_t readbytes = 0;
	try {
		file_.read(buffer, size);
		transfferBytes_ += size;
	}
	catch (const std::exception& err) {
		std::cerr << err.what() << std::endl;
		this->close();
		return -1;
	}
	return file_.gcount();
}

bool FileReadStruct::isProcessFinish()
{
	return bytesHasRead_ == fileSize_;
}

std::size_t FileReadStruct::getFileSize()
{
	file_.seekg(0, std::ios::end);
	std::size_t filesize = file_.tellg();
	file_.seekg(0, std::ios::beg);
	return filesize;
}

bool FileWriteStruct::openFile(const std::string& fileName)
{
	fileName_ = fileName;
	if (std::filesystem::exists(fileName)) {
		if (!std::filesystem::remove(fileName)) {
			return false;
		}
	}
	file_.open(fileName, std::ios::out | std::ios::binary);
	return file_.is_open();
}

std::size_t FileWriteStruct::processBytes(char* buffer, size_t size)
{
	return writeBytes(buffer, size);
}

std::size_t FileWriteStruct::writeBytes(char* buffer, size_t size)
{
	std::streampos before = file_.tellp();
	try {
		file_.write(buffer, size);
		transfferBytes_ += size;
	}
	catch (const std::exception& err) {
		std::cerr << err.what() << std::endl;
		this->close();
		return -1;
	}
	std::streampos after = file_.tellp();
	return after - before;
}

bool FileAppendStruct::openFile(const std::string& fileName)
{
	fileName_ = fileName;
	if (std::filesystem::exists(fileName)) {
		if (!std::filesystem::remove(fileName)) {
			return false;
		}
	}
	file_.open(fileName, std::ios::app | std::ios::binary);
	return file_.is_open();
}

std::size_t FileAppendStruct::processBytes(char* buffer, size_t size)
{
	return appendBytes(buffer, size);
}

std::size_t FileAppendStruct::appendBytes(char* buffer, size_t size)
{
	std::streampos before = file_.tellp();
	try {
		file_.write(buffer, size);
		transfferBytes_ += size;
	}
	catch (const std::exception& err) {
		std::cerr << err.what() << std::endl;
		this->close();
		return -1;
	}
	std::streampos after = file_.tellp();
	return after - before;
}
